class CommentsController < ApplicationController
  before_filter :find_comment, :only => [:destroy]
  before_filter :login_required  
  
  def create
    root_id = params[:comment].delete(:root_id)
    comment = Comment.new(params[:comment])
		if (!logged_in? && comment.valid_with_captcha?) || (logged_in? && comment.valid?)
    	comment.user_id = logged_in? ? current_user.id : User::DEFAULT_ID
			comment.root_id = root_id
			comment.save!

			unless root_id.blank?
				@root = Comment.find_by_id(root_id)
				unless @root.nil?
					comment.root = @root
					@root.add_child(comment)
				end
			end
		else
			flash[:current_comment] = comment
    end
		redirect_to params[:referrer].blank? ? '/' : params[:referrer]
  end
  
  def update
  	if params[:comments]
	  	@comments = Comment.find(params[:comments])
	  	@post = Post.find(params[:model])
	  	is_allow = (@post.user == current_user || current_user.admin?)
	  	case params[:comment_action].to_i
	  	when 1 #Скрыть
	  		@comments.each do |comment|
	  			comment.update_attribute(:is_visible, false) if comment.user == current_user || is_allow
	  		end
	  	when 2 #Удалить
	  		@comments.each do |comment|
	  			comment.destroy if comment.user == current_user || is_allow
	  		end
	  	end
  	end
  	redirect_to params[:referrer].blank? ? '/' : params[:referrer]
  end
  
  def destroy
    @comment.destroy
    redirect_to :back
  end
    
  private
  
  def authorized?
    ['create', 'update' ].include?(action_name) || (['destroy'].include?(action_name) && (current_user == @comment.user))
  end
  
  def find_comment
    @comment = Comment.find(params[:id])
  end 
end
